// pages/Attachment/Attachment.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    achieveIndex: Array.from({ length: 8 }, (_, index) => 0),
    imgSrc: Array.from({ length: 7 }, (_, index) => null), // => 该变量不可以设置为全局 也不可以设置为本地缓存 离开该界面后立刻销毁
    foverSrc: Array.from({ length: 8 }, () => []),  // => 该变量不可以设置为全局 也不可以设置为本地缓存 离开该界面后立刻销毁
    textlist:[
      {
        id:0,
        msg:'File 1:身份证正反面'
      },
      {
        id:1,
        msg:'File 2:本硕学历学位证书'
      },
      {
        id:2,
        msg:'File 3:电子备案表'
      },
      {
        id:3,
        msg:'File 4:在读证明(就业推荐表或在线验证报告)'
      },
      {
        id:4,
        msg:'File 5:辅导员岗要求证明(党员证明及学生干部证明)，教师岗位可不选'
      },
      {
        id:5,
        msg:'File 6:教师岗要求证明(论文或竞赛材料)，辅导员岗位可不选'
      },
      {
        id:6,
        msg:'File 7:其他科研或获奖证明材料'
      },
      {
        id:7,
        msg:'File 8:上传报名表'
      }
    ],
    btnisshow:false,// 确定提交按钮的显示与否 默认为false通过上传附件成功后改变该值来显示确定提交按钮;
  },

// * 方案二 集中上传

// => 收集链接

async fileDate(event) {
  let achieveIndex = await wx.getStorageSync('achieveIndex')
  const openid = await wx.getStorageSync('openid')
  const db = wx.cloud.database()
  const that = this
  console.log(event.currentTarget.dataset.index)
  let index = event.currentTarget.dataset.index
  switch (event.currentTarget.dataset.index) {
    case 0:
        await wx.chooseMedia({
         count: 15,
         type: "image",
         sourceType: ['album', 'camera'],
         success: function(res) {
         console.log(res.tempFiles)
         if(res.tempFiles){
           const linkArray = res.tempFiles.map(item => item.tempFilePath)  // =>=> 解决用户一次提交多张图片
           that.data.imgSrc[0] = linkArray  
           let newArray = that.data.achieveIndex.slice()
           newArray[0] = 1
           that.setData({
             achieveIndex: newArray
           })
           // 上传图片到云存储 、设置唯一命名 、 拼接永久链接       
           function gotoCloud(filePath, cloudPath) { 
             return new Promise((resolve, reject) => {
               wx.cloud.uploadFile({
                 filePath: filePath,
                 cloudPath: cloudPath,
                 success: res => {
                  wx.showToast({
                    title: '身份证正反面上传成功',
                    icon: 'none'
                  })
                   resolve(res.fileID)
                 },
                 fail: err => {
                   reject(err)
                 }
               })
             })
           }
           // 调用 gotoCloud 函数
           for (let i = 0; i < linkArray.length; i++) {
             const imagePath = linkArray[i]
             const timestamp = new Date().getTime()
             const extension = imagePath.split('.').pop()
             const cloudPath = `applicantCertificate/${timestamp}_${openid}_${index}_${i}.${extension}`
             // https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/1693145004850_oM7WQ6956w1rtZi0_fcGNnmCJDmw.png
               // => 永久链接 = https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/ + 图片名
             const foverSrc = 'https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/' + cloudPath
             that.data.foverSrc[0].push(foverSrc)
             gotoCloud(imagePath, cloudPath)
               .then(fileID => {
                 console.log('上传成功：', fileID)
               })
               .catch(error => {
                 console.error('上传失败：', error)
               });
           }
         }
       },
         fail: function(err) {
         console.error(err)
       }
     })
       // console.log('身份证正反面');
       break;
  
    case 1:
        await wx.chooseMessageFile({
        count: 15,
        type: "all",
        success: function(res) {
        console.log(res.tempFiles)
        if(res.tempFiles){
          const linkArray = res.tempFiles.map(item => item.path)  // =>=> 解决用户一次提交多个附件
          that.data.imgSrc[1] = linkArray
          let newArray = that.data.achieveIndex.slice()
          newArray[1] = 1
          that.setData({
            achieveIndex: newArray
          })
          // 上传图片到云存储 、设置唯一命名 、 拼接永久链接       
          function gotoCloud(filePath, cloudPath) {
            return new Promise((resolve, reject) => {
              wx.cloud.uploadFile({
                filePath: filePath,
                cloudPath: cloudPath,
                success: res => {
                  wx.showToast({
                    title: '本科学历学位书上传成功',
                    icon: 'none'
                  })
                  resolve(res.fileID)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
          // 调用 gotoCloud 函数
          for (let i = 0; i < linkArray.length; i++) {
            const imagePath = linkArray[i]
            const timestamp = new Date().getTime()
            const extension = imagePath.split('.').pop()
            const cloudPath = `applicantCertificate/${timestamp}_${openid}_${index}_${i}.${extension}`
            // https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/1693145004850_oM7WQ6956w1rtZi0_fcGNnmCJDmw.png
              // => 永久链接 = https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/ + 图片名
            const foverSrc = 'https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/' + cloudPath
            that.data.foverSrc[1].push(foverSrc)
            gotoCloud(imagePath, cloudPath)
              .then(fileID => {
                console.log('上传成功：', fileID)
              })
              .catch(error => {
                console.error('上传失败：', error)
              });
          }
        }
      },
        fail: function(err) {
        console.error(err)
      }
    })
      // console.log('本硕学历学位证书');
      break;
  
    case 2:
        await wx.chooseMessageFile({
        count: 15,
        type: "all",
        success: function(res) {
        console.log(res.tempFiles)
        if(res.tempFiles){
          const linkArray = res.tempFiles.map(item => item.path)  // =>=> 解决用户一次提交多个附件
          that.data.imgSrc[1] = linkArray
          let newArray = that.data.achieveIndex.slice()
          newArray[2] = 1
          that.setData({
            achieveIndex: newArray
          })
          // 上传图片到云存储 、设置唯一命名 、 拼接永久链接       
          function gotoCloud(filePath, cloudPath) {
            return new Promise((resolve, reject) => {
              wx.cloud.uploadFile({
                filePath: filePath,
                cloudPath: cloudPath,
                success: res => {
                  wx.showToast({
                    title: '电子备案表上传成功',
                    icon: 'none'
                  })
                  resolve(res.fileID)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
          // 调用 gotoCloud 函数
          for (let i = 0; i < linkArray.length; i++) {
            const imagePath = linkArray[i]
            const timestamp = new Date().getTime()
            const extension = imagePath.split('.').pop()
            const cloudPath = `applicantCertificate/${timestamp}_${openid}_${index}_${i}.${extension}`
            // https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/1693145004850_oM7WQ6956w1rtZi0_fcGNnmCJDmw.png
              // => 永久链接 = https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/ + 图片名
            const foverSrc = 'https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/' + cloudPath
            that.data.foverSrc[2].push(foverSrc)
            gotoCloud(imagePath, cloudPath)
              .then(fileID => {
                console.log('上传成功：', fileID)
              })
              .catch(error => {
                console.error('上传失败：', error)
              });
          }
        }
      },
        fail: function(err) {
        console.error(err)
      }
    })
      // console.log('电子备案表');
      break;
  
    case 3:
        await wx.chooseMessageFile({
        count: 15,
        type: "all",
        success: function(res) {
        console.log(res.tempFiles)
        if(res.tempFiles){
          const linkArray = res.tempFiles.map(item => item.path)  // =>=> 解决用户一次提交多个附件
          that.data.imgSrc[3] = linkArray
          let newArray = that.data.achieveIndex.slice()
          newArray[3] = 1
          that.setData({
            achieveIndex: newArray
          })
          // 上传图片到云存储 、设置唯一命名 、 拼接永久链接       
          function gotoCloud(filePath, cloudPath) {
            return new Promise((resolve, reject) => {
              wx.cloud.uploadFile({
                filePath: filePath,
                cloudPath: cloudPath,
                success: res => {
                  wx.showToast({
                    title: '在读证明上传成功',
                    icon: 'none'
                  })
                  resolve(res.fileID)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
          // 调用 gotoCloud 函数
          // => 解决用户一次上传多张
          for (let i = 0; i < linkArray.length; i++) {
            const imagePath = linkArray[i]
            const timestamp = new Date().getTime()
            const extension = imagePath.split('.').pop()
            const cloudPath = `applicantCertificate/${timestamp}_${openid}_${index}_${i}.${extension}`
            // https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/1693145004850_oM7WQ6956w1rtZi0_fcGNnmCJDmw.png
              // => 永久链接 = https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/ + 图片名
            const foverSrc = 'https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/' + cloudPath
            that.data.foverSrc[3].push(foverSrc)
            gotoCloud(imagePath, cloudPath)
              .then(fileID => {
                console.log('上传成功：', fileID)
              })
              .catch(error => {
                console.error('上传失败：', error)
              });
          }
        }
      },
        fail: function(err) {
        console.error(err)
      }
    })
      // console.log('在读证明');
      break;
    
    case 4:
        await wx.chooseMessageFile({
        count: 15,
        type: "all",
        success: function(res) {
        console.log(res.tempFiles)
        if(res.tempFiles){
          const linkArray = res.tempFiles.map(item => item.path)  // =>=> 解决用户一次提交多个附件
          that.data.imgSrc[3] = linkArray
          let newArray = that.data.achieveIndex.slice()
          newArray[4] = 1
          that.setData({
            achieveIndex: newArray
          }) 
          // 上传图片到云存储 、设置唯一命名 、 拼接永久链接       
          function gotoCloud(filePath, cloudPath) {
            return new Promise((resolve, reject) => {
              wx.cloud.uploadFile({
                filePath: filePath,
                cloudPath: cloudPath,
                success: res => {
                  wx.showToast({
                    title: '辅导员要求证明上传成功',
                    icon: 'none'
                  })
                  resolve(res.fileID)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
          // 调用 gotoCloud 函数
          for (let i = 0; i < linkArray.length; i++) {
            const imagePath = linkArray[i]
            const timestamp = new Date().getTime()
            const extension = imagePath.split('.').pop()
            const cloudPath = `applicantCertificate/${timestamp}_${openid}_${index}_${i}.${extension}`
            // https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/1693145004850_oM7WQ6956w1rtZi0_fcGNnmCJDmw.png
              // => 永久链接 = https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/ + 图片名
            const foverSrc = 'https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/' + cloudPath
            that.data.foverSrc[4].push(foverSrc)
            gotoCloud(imagePath, cloudPath)
              .then(fileID => {
                console.log('上传成功：', fileID)
              })
              .catch(error => {
                console.error('上传失败：', error)
              });
          }
        }
      },
        fail: function(err) {
        console.error(err)
      }
    })
      // console.log('辅导员岗要求证明');
      break;
    
    case 5:
       await wx.chooseMessageFile({
        count: 15,
        type: "all",
        success: function(res) {
        console.log(res.tempFiles)
        if(res.tempFiles){
          const linkArray = res.tempFiles.map(item => item.path)  // =>=> 解决用户一次提交多个附件
          that.data.imgSrc[5] = linkArray
          let newArray = that.data.achieveIndex.slice()
          newArray[5] = 1
          that.setData({
            achieveIndex: newArray
          }) 
          // wx.setStorageSync('achieveIndex', achieveIndex)
          // 上传图片到云存储 、设置唯一命名 、 拼接永久链接       
          function gotoCloud(filePath, cloudPath) {
            return new Promise((resolve, reject) => {
              wx.cloud.uploadFile({
                filePath: filePath,
                cloudPath: cloudPath,
                success: res => {
                  wx.showToast({
                    title: '教师要求证明上传成功',
                    icon: 'none'
                  })
                  resolve(res.fileID)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
          // 调用 gotoCloud 函数
          for (let i = 0; i < linkArray.length; i++) {
            const imagePath = linkArray[i]
            const timestamp = new Date().getTime()
            const extension = imagePath.split('.').pop()
            const cloudPath = `applicantCertificate/${timestamp}_${openid}_${index}_${i}.${extension}`
            // https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/1693145004850_oM7WQ6956w1rtZi0_fcGNnmCJDmw.png
              // => 永久链接 = https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/ + 图片名
            const foverSrc = 'https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/' + cloudPath
            that.data.foverSrc[5].push(foverSrc)
            gotoCloud(imagePath, cloudPath)
              .then(fileID => {
                console.log('上传成功：', fileID)
              })
              .catch(error => {
                console.error('上传失败：', error)
              });
          }
        }
      },
        fail: function(err) {
        console.error(err)
      }
    })
      // console.log('教师岗要求证明');
      break;

    case 6:
       await wx.chooseMessageFile({
        count: 3,
        type: "all",
        // sourceType: ['album', 'camera'],
        success: function(res) {
        console.log(res.tempFiles)  // => [{....}]
        console.log(res.tempFiles[0]) // { ... }
        if(res.tempFiles){
          // =>=> 获得其临时链接 res.tempFiles [{....}]
          const linkArray = res.tempFiles.map(item => item.path)  // =>=> 解决用户一次提交多个附件
          that.data.imgSrc[6] = linkArray
          // =>=> 成功变色
          let newArray = that.data.achieveIndex.slice()
          newArray[6] = 1
          that.setData({
            achieveIndex: newArray
          }) 
          // 上传图片到云存储 、设置唯一命名 、 拼接永久链接       
          function gotoCloud(filePath, cloudPath) {
            return new Promise((resolve, reject) => {
              wx.cloud.uploadFile({
                filePath: filePath,
                cloudPath: cloudPath,
                success: res => {
                  wx.showToast({
                    title: '其它科研或获奖证明材料上传成功',
                    icon: 'none'
                  })
                  resolve(res.fileID)
                },
                fail: err => {
                  reject(err)
                }
              })
            })
          }
          // 调用 gotoCloud 函数
          for (let i = 0; i < linkArray.length; i++) {
            const imagePath = linkArray[i]
            const timestamp = new Date().getTime()
            const extension = imagePath.split('.').pop()
            const cloudPath = `applicantCertificate/${timestamp}_${openid}_${index}_${i}.${extension}`
            // https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/1693145004850_oM7WQ6956w1rtZi0_fcGNnmCJDmw.png
              // => 永久链接 = https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/applicantCertificate/ + 图片名
            const foverSrc = 'https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/' + cloudPath
            that.data.foverSrc[6].push(foverSrc)
            gotoCloud(imagePath, cloudPath)
              .then(fileID => {
                console.log('上传成功：', fileID)
              })
              .catch(error => {
                console.error('上传失败：', error)
              });
          }

          }
        },
        fail: function(err) {
        console.error(err)
      }
    })
      // console.log('其他科研或获奖证明材料');
      break;

    case 7: 
        await wx.chooseMessageFile({
          count: 1,  // => 限制用户只能一个一个上传
          type: 'all',
          success: function(res) {
            console.log(res.tempFiles[0])
            let filePath = res.tempFiles[0].path  // 临时链接 res.tempFiles[0].path
            let timestamp = new Date().getTime()
            let extension = filePath.split('.').pop()
            let cloudPath =  `userTable/${openid}_${timestamp}.${extension}`
            let fileSrc = 'https://636c-cloud1-7g5ffdpz146dadd4-1319236987.tcb.qcloud.la/' + cloudPath
            that.data.foverSrc[7].push(fileSrc)
            console.log(that.data.foverSrc[7])
            wx.cloud.uploadFile({
              filePath: filePath,
              cloudPath: cloudPath,  // => 对应文件夹 + 文件名
              success: function(res) {
                let newArray = that.data.achieveIndex.slice()
                newArray[7] = 1
                that.setData({
                  achieveIndex: newArray
                })
                wx.showToast({
                  title: '报名表上传成功',
                  icon: 'none'
                })
                 console.log('附件上传成功',res)
              },
              fail: function(err) {
                console.log('附件上传失败',err)
              }
            })
         },
          fail: function(err) {
          console.error(err)
        }
      })

      break;
  }
},

upload: function() {
  const openid = wx.getStorageSync('openid')
  let basic = wx.getStorageSync('basic')
  let main = wx.getStorageSync('main')
  let record = wx.getStorageSync('record')
  let foverSrc = wx.getStorageSync('foverSrc')
  // 汇总 3 页数据

  let userInfo = {
    basic,
    main,
    // imgSrc: this.data.imgSrc,
    foverSrc: this.data.foverSrc
  };

  // 数据库操作
  const db = wx.cloud.database()
  if (record == 'true') {
    db.collection('applicant').add({
      data: {
        userInfo
      },
      success: (res) => {
        wx.setStorageSync('record', 'false')
        console.log('保存成功', res)
      },
      fail: (err) => {
        console.log('保存失败', err)
      }
    })
  } else {
    db.collection('applicant').where({
      _openid: openid
    }).get({
      success: (res) => {
        if (res.data.length > 0) {
          const id = res.data[0]._id
          db.collection('applicant').doc(id).set({
            data: { userInfo },
            success: (res) => {
              console.log('更新成功', res)
            },
            fail: (err) => {
              console.log('更新失败', err)
            }
          })
        } else {
          console.log('找不到匹配的记录')
        }
      },
      fail: (err) => {
        console.error('查询失败', err)
      }
    });
  }
},

success() {
  let foverSrc = this.data.foverSrc
  if(foverSrc[7].length === 0) {
    wx.showToast({
      title: '请确保报名表项上传成功',
      icon: 'none'
    })
    return
  }
  if(foverSrc[0].length === 0 || foverSrc[1].length === 0 || foverSrc[2].length === 0 || foverSrc[3].length === 0 || foverSrc[6].length === 0) {
    wx.showToast({
      title: '请确保 File : 1 2 3 4 7 项成功上传',
      icon: 'none'
    })
    return
  }
  wx.showModal({
    title: '你确定提交吗？',
    content: '确定则提交，否则取消提交',
    cancelColor:'#c43739',
    confirmColor:'#1f3696',
    complete: async (res) => {
      if (res.cancel) {
        wx.showToast({
          title: '已取消',
          icon:'success'
        })
      }
      if (res.confirm) {
        wx.showToast({
          title: '您已提交成功',
          icon:'success',
        })
        this.upload() // => 调用数据库操作函数
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/sign/sign'
          });
        }, 2000) // 设置 3 秒后跳转
      }
    }
  })
},

// => 修改记录验证

onLoad() {
  let achieveIndex = wx.getStorageSync('achieveIndex')
  let record = wx.getStorageSync('record')
  let foverSrcArr = wx.getStorageSync('foverSrc')
  if(foverSrcArr === '' && achieveIndex === '') {
     console.log('本地未缓存')
  } else {
    this.data.foverSrc = foverSrcArr
    this.setData({
      achieveIndex
    })
  }
  if(record === '') {
    wx.setStorageSync('record', 'true')
  } else {
    wx.setStorageSync('record', 'false') 
  }
},

// => 页面销毁

onUnload() {
  console.log(this.data.foverSrc)
  console.log(this.data.achieveIndex)
  wx.setStorageSync('foverSrc', this.data.foverSrc)
  wx.setStorageSync('achieveIndex', this.data.achieveIndex)
}
})